/*
ansible命令行工具封装
*/
package tools

import (
	"gitee.com/lllgo/gopkg/exec"
	"strings"
)

type Runner interface {
	Run() error
}

/*playbook结构封装*/
type Playbook struct {
	ansibleDir    string
	InventoryPath string
	PlaybookPaths []string
	Tags          []string
	Params        map[string]string
	Args          []string
}

func NewPlaybook(ansibleDir, inventoryPath string, playbookPaths ...string) *Playbook {
	return &Playbook{
		ansibleDir:    ansibleDir,
		InventoryPath: inventoryPath,
		PlaybookPaths: playbookPaths,
	}
}

func (p *Playbook) Run() error {
	args := make([]string, 0, 8)

	if p.InventoryPath != "" {
		args = append(args, "-i", p.InventoryPath)
	}

	// 多tag用","分隔  参考博客：https://www.zsythink.net/archives/2641
	if len(p.Tags) != 0 {
		args = append(args, "--tags", strings.Join(p.Tags, ","))
	}

	// 多param用" "分隔
	if len(p.Params) != 0 {
		for k, v := range p.Params {
			args = append(args, "-e", k+"="+v)
		}
	}

	args = append(args, p.PlaybookPaths...)
	if len(p.Args) > 0 {
		args = append(args, p.Args...)
	}

	// 不管执行的结果 利用ansible自身特性排查问题
	_ = exec.Cmd("ansible-playbook", p.ansibleDir, args...)
	return nil
}
